package com.android.tiango.baba.fragment;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseFragment;
import com.android.tiango.baba.act.ActAdressList;
import com.android.tiango.baba.act.ActLogin;
import com.android.tiango.baba.act.ActMessageCenter;
import com.android.tiango.baba.act.ActMyBaoBeiList;
import com.android.tiango.baba.act.ActMyDatum;
import com.android.tiango.baba.act.ActMyTask;
import com.android.tiango.baba.act.ActPosts;
import com.android.tiango.baba.act.ActSetting;
import com.android.tiango.baba.act.ActShare;
import com.android.tiango.baba.act.ActShareGoods;
import com.android.tiango.baba.act.ActZoeCollection;
import com.android.tiango.baba.adapter.DatumTagAdapter;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.entity.UserInfoEntity;
import com.android.tiango.baba.entity.UserModel;
import com.android.tiango.baba.entity.UserTagEntity;
import com.android.tiango.baba.entity.UserTagModel;
import com.android.tiango.baba.util.ImageLoader;
import com.android.tiango.baba.util.StringUtils;
import com.android.tiango.baba.util.UserTagUtil;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.MeasureGridView;
import com.android.tiango.baba.view.RoundImageView;
import com.android.tiango.baba.view.ScrollableImageView;

/**
 * 用户中心
 * @author txg
 * 
 */
public class FrUserInfo extends BaBaseFragment implements OnClickListener {
	private ScrollableImageView mBlurxAredImageHeader;
	private TextView mTv_mybaby, mTv_Mysave, mTv_Posts, mTv_Mytask, mTv_Message, mTv_Address,mTv_Seting;
	private RelativeLayout mRl_content;
	private boolean mIsLogin = false;
	private Button mBtnLogin;
	private UserModel mModel;
	private DatumTagAdapter mAdapter;
	private MeasureGridView mGListview; 
	private RoundImageView mHead;
	private ImageView mLevel,mSex;
	private TextView  mName,mintegral,mtgointg;
	private ImageLoader mLoader;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(ShareCookie.isLoginAuth()){
			mIsLogin = true;
		}
		mLoader = new ImageLoader(getActivity(), R.drawable.bg_head_def);
	}
 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = null;
		if (mIsLogin) {
			view = inflater.inflate(R.layout.layout_myzoe, null);
		} else {
			view = inflater.inflate(R.layout.layout_myzoe_def, null);
			mBtnLogin = (Button) view.findViewById(R.id.btn_Login);
			mBtnLogin.setOnClickListener(this);
		}
		init(view);
		return view;
	}
	
	private void init(View view) {
		mTitleBar = (AppTitleBar) view.findViewById(R.id.titlebar);
		mTv_mybaby = (TextView) view.findViewById(R.id.tv_mybaby);
		mTv_Mysave = (TextView) view.findViewById(R.id.tv_mysave);
		mTv_Posts = (TextView) view.findViewById(R.id.tv_posts);
		mTv_Mytask = (TextView) view.findViewById(R.id.tv_mytask);
		mTv_Message = (TextView) view.findViewById(R.id.tv_message);
		mTv_Address = (TextView) view.findViewById(R.id.tv_address);
		mTv_Seting = (TextView) view.findViewById(R.id.tv_seting);

		mTv_mybaby.setOnClickListener(this);
		mTv_Mysave.setOnClickListener(this);
		mTv_Posts.setOnClickListener(this);
		mTv_Mytask.setOnClickListener(this);
		mTv_Message.setOnClickListener(this);
		mTv_Address.setOnClickListener(this);
		mTv_Seting.setOnClickListener(this);
		
		if (mIsLogin) {
			doGetUserInfo();
			mGListview = (MeasureGridView)view.findViewById(R.id.ml_listview);
			mRl_content = (RelativeLayout) view.findViewById(R.id.ly_content); 
			int screenWidth = getScreenWidth(getActivity()); 
			Bitmap bmpBlurred = BitmapFactory.decodeResource(getResources(),R.drawable.bg_login_def); 
			if (bmpBlurred != null) {
				bmpBlurred = Bitmap.createScaledBitmap(bmpBlurred, screenWidth,
						(int) (bmpBlurred.getHeight() * ((float) screenWidth) / (float) bmpBlurred
								.getWidth()), false); 
			}
			mRl_content.setOnClickListener(this); 
			mGListview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					// 个人资料
					startActivityForResult(new Intent(getActivity(), ActMyDatum.class), 200);
				}
			});
			mHead = (RoundImageView)view.findViewById(R.id.iv_head);
			mName = (TextView)view.findViewById(R.id.tv_name) ;
			mLevel = (ImageView)view.findViewById(R.id.iv_level); 
			mSex = (ImageView)view.findViewById(R.id.iv_sex);
			mintegral = (TextView)view.findViewById(R.id.tv_integral) ;
			mtgointg = (TextView)view.findViewById(R.id.tv_tgointg); 
		} 
	}

	private void setVal() {
		//图片
		mLoader.loadImage(mModel.getAvatarUrl(), mHead);
		System.out.println("img:"+mModel.getAvatarUrl());
		//昵称
		if(!StringUtils.isEmpty(mModel.getNickName())) {
			mName.setText(mModel.getNickName());
		}else{
			mName.setText("暂无");
		}
		//积分
		if( mModel.getIntegral()>0){
			mintegral.setText(""+mModel.getIntegral());
		}else{
			mintegral.setText("0");
		}
		//天购币
		if(mModel.getTgoCurrency() > 0){
			mtgointg.setText(mModel.getTgoCurrency()+"");
		}else{
			mtgointg.setText("0");
		}
//			iv_Level.setb
		int sexType = mModel.getGender();
		switch (sexType) {
		case 0: 
			mSex.setVisibility(View.GONE);
			break;
		case 1: 
			mSex.setVisibility(View.VISIBLE);
			mSex.setBackgroundResource(R.drawable.bg_sex);
			break;
		case 2: 
			mSex.setVisibility(View.VISIBLE);
			mSex.setBackgroundResource(R.drawable.bg_sex_girl);
			break;
		}
		if(mModel.getUserTags() != null && mModel.getUserTags().size() > 0){ 
			setTagUi(mModel.getUserTags());
		}else{
			doUserTag();
		}
	}
	
	private void doGetUserInfo() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams params = new HttpParams();
		final String token = ShareCookie.getToken();
		params.put("token", token);
		// client.setmToken(ShareCookie.getToken());
		client.get(HttpUrl.getUrl(HttpUrl.USERINFO), params,
				new HttpCallBack() {
					@Override
					public void onHttpSuccess(Object arg0) {
						dismissWaitingDialog();
						UserInfoEntity entity = (UserInfoEntity) arg0;
						mModel = entity.getData();
						mModel.setToken(token);
						ShareCookie.saveUserInfo(mModel);
						setVal();
					}

					@Override
					public void onHttpStarted() {
						showWaitingDialog();
					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();
						mModel = ShareCookie.getUserInfo();
						setVal();
					}
				}, UserInfoEntity.class);//
	}
	
	private void doUserTag() {
		HttpClientAsync client = HttpClientAsync.getInstance();
		HttpParams httpParams = new HttpParams();
		httpParams.put("token", mModel.getToken());
		httpParams.put("version", "1.0");
		client.get(HttpUrl.getUrl(HttpUrl.USERTAGS), httpParams, new HttpCallBack() { 
				public void onHttpFailure(Exception arg0, String arg1) {
					dismissWaitingDialog();
					if (!StringUtils.isEmpty(arg1)) {
						Toast.makeText(getActivity(), arg1, Toast.LENGTH_LONG).show();
					}
				} 
				@Override
				public void onHttpStarted() {
					showWaitingDialog();
				}

				@Override
				public void onHttpSuccess(Object arg0) {
					dismissWaitingDialog();
					UserTagEntity entity = (UserTagEntity) arg0;
					ArrayList<UserTagModel> data = entity.getData();
					if (data != null && data.size() > 0) {
						data = UserTagUtil.shortUserTagData(data);
						mModel.setUserTags(data);
						//重新储存
						ShareCookie.saveUserInfo(mModel);
						setTagUi(data);
					}
				}
				}, UserTagEntity.class);
	}
	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) { 
		super.onActivityCreated(savedInstanceState); 
		if (null != mTitleBar) {
			mTitleBar.setTitle(getString(R.string.userconter));
			mTitleBar.setImageNotBackGround();
			mTitleBar.setMoreIcon(R.drawable.bg_talkx);
			mTitleBar.setMoreImageOnClickListener(this);
		}
		
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tv_mybaby:// 我的宝贝
			if (mIsLogin) {
				showActivity(ActMyBaoBeiList.class);
			}
			break;
		case R.id.tv_mysave:
			// 我的收藏
			showActivity(ActZoeCollection.class);
			break;
		case R.id.tv_posts:
			// 我的帖子
			showActivity(ActPosts.class);
			break;
		case R.id.tv_mytask:// 我的任务
//			if (mIsLogin) {
				showActivity(ActMyTask.class);
//			} else {
//				showActivity(ActLogin.class);
//			} 
			break;
		case R.id.tv_message:// 我的消息
			if (mIsLogin) {
				showActivity(ActMessageCenter.class);
			}
			break;
		case R.id.tv_address:// 我的地址
//			if (mIsLogin) {
				showActivity(ActAdressList.class);
//			}
			break;
		case R.id.tv_seting: // 设置
			if (mIsLogin) {
				showActivity(ActSetting.class);
			}
			break;
		case R.id.ly_content:
			// 个人资料
			startActivityForResult(new Intent(getActivity(), ActMyDatum.class), 200);  
			break;
		case R.id.titlebar_more: 
			showActivity(ActShare.class);
			break;
		case R.id.btn_Login:
			showActivity(ActLogin.class);
			break;
		}
	}

	 
	//更新标签
	private void setTagUi(ArrayList<UserTagModel> data) {
		int count = data.size() >=5 ? 5 : data.size();
		mAdapter = new DatumTagAdapter(getActivity(), data , count);
		mGListview.setAdapter(mAdapter);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		 if(200 == resultCode)  {
			 doGetUserInfo();
		 }  
		 super.onActivityResult(requestCode, resultCode, data);  
	}
		
	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public static int getScreenWidth(Activity context) {
		Display display = context.getWindowManager().getDefaultDisplay();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			Point size = new Point();
			display.getSize(size);
			return size.x;
		}
		return display.getWidth();
	}

}
